package cn.bulgat.spring.web.controller;

import cn.bulgat.common.exception.CustomException;
import cn.bulgat.common.exception.ThrowUtils;
import cn.bulgat.common.model.BaseResp;
import cn.bulgat.common.model.DelReq;
import cn.bulgat.common.model.RespCode;
import cn.bulgat.common.utils.RespUtils;
import cn.bulgat.spring.web.annotation.AuthCheck;
import cn.bulgat.spring.web.constant.UserConstant;
import cn.bulgat.spring.web.model.entity.User;
import cn.bulgat.spring.web.model.req.user.*;
import cn.bulgat.spring.web.model.vo.LoginUserVO;
import cn.bulgat.spring.web.model.vo.UserVO;
import cn.bulgat.spring.web.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户接口
 *
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    // region 登录相关

    /**
     * 用户注册
     *
     * @param registerReq
     * @return
     */
    @PostMapping("/register")
    public BaseResp<Long> register(@RequestBody RegisterReq registerReq) {
        if (registerReq == null) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        String username = registerReq.getUsername();
        String password = registerReq.getPassword();
        String confirmPassword = registerReq.getConfirmPassword();

        if (StringUtils.isAnyBlank(username, password, confirmPassword)) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        long result = userService.register(username, password, confirmPassword);
        return RespUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param loginReq
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResp<LoginUserVO> login(@RequestBody LoginReq loginReq, HttpServletRequest request) {
        if (loginReq == null) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        String username = loginReq.getUsername();
        String password = loginReq.getPassword();
        if (StringUtils.isAnyBlank(username, password)) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.login(username, password, request);
        return RespUtils.success(loginUserVO);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResp<Boolean> logout(HttpServletRequest request) {
        if (request == null) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        boolean result = userService.logout(request);
        return RespUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResp<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return RespUtils.success(userService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param addReq
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResp<Long> addUser(@RequestBody AddReq addReq, HttpServletRequest request) {
        if (addReq == null) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        Long id=userService.addUser(addReq);
        return RespUtils.success(id);
    }

    /**
     * 删除用户
     *
     * @param delReq
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResp<Boolean> delUser(@RequestBody DelReq<Long> delReq, HttpServletRequest request) {
        if (delReq == null || delReq.getId() <= 0) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(delReq.getId());
        return RespUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param updateReq
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResp<Boolean> updateUser(@RequestBody UpdateReq updateReq,
                                              HttpServletRequest request) {
        if (updateReq == null || updateReq.getId() == null) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(updateReq, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, RespCode.OPERATION_ERROR);
        return RespUtils.success(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResp<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, RespCode.NOT_FOUND_ERROR);
        return RespUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResp<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResp<User> response = getUserById(id, request);
        User user = response.getData();
        return RespUtils.success(userService.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param queryReq
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResp<Page<User>> listUserPage(@RequestBody QueryReq queryReq,
                                             HttpServletRequest request) {
        long current = queryReq.getCurrent();
        long size = queryReq.getSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(queryReq));
        return RespUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param queryReq
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResp<Page<UserVO>> listUserVOPage(@RequestBody QueryReq queryReq,
                                                 HttpServletRequest request) {
        if (queryReq == null) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        long current = queryReq.getCurrent();
        long size = queryReq.getSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, RespCode.PARAMS_ERROR);
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(queryReq));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return RespUtils.success(userVOPage);
    }

    // endregion

    /**
     * 更新个人信息
     *
     * @param updateMyselfReq
     * @param request
     * @return
     */
    @PostMapping("/update/myself")
    public BaseResp<Boolean> updateMyself(@RequestBody UpdateMyselfReq updateMyselfReq,
                                          HttpServletRequest request) {
        if (updateMyselfReq == null) {
            throw new CustomException(RespCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(updateMyselfReq, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, RespCode.OPERATION_ERROR);
        return RespUtils.success(true);
    }
}
